<template>
  <van-sticky>
    <van-nav-bar
      title="收货地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
  </van-sticky>

  <van-address-list
    v-model="selectedAddressId"
    :list="list"
    default-tag-text="默认"
    @add="ToAdd"
    @edit="ToEdit"
    @select="onSelected"
  />
</template>

<script setup>

const { proxy } = getCurrentInstance();

const selectedAddressId = ref(0);
const list = reactive([]); //地址列表数据
const busid = proxy.$cookies.get('business').id;
// 调用生命周期
onBeforeMount(() => {
  getAddressData();
});

// 获取当前登录用户的收货地址
const getAddressData = async () => {
  let data = {
    busid: busid,
  };

  let result = await proxy.$post({
    url: "business/address/index",
    params: data,
  });

  if (result.code === 1) {
    // 把list数组清空
    list.length = 0;

    for (let item of result.data) {
      list.push({
        id: item.id,
        name: item.consignee,
        tel: item.mobile,
        address:
          item.provinces.name +
          item.citys.name +
          item.districts.name +
          item.address,
        isDefault: item.status == 1 ? true : false,
      });

      if (item.status == 1) {
        selectedAddressId.value = item.id;
      }
    }

    return false;
  } else {
    proxy.$NotifyWarn(result.msg);

    return false;
  }
};

const onSelected = async (values) => {
    let params = {
        busid:busid,
        id:values.id
    }

    let result = await proxy.$post({
        url:'/business/address/selected',
        params
    })

    if(result.code === 1)
    {
        selectedAddressId.value = values.id;

        getAddressData();

        proxy.$NotifySuccess(result.msg);

        return false;
    }else{
        proxy.$NotifyWarn(result.msg);

        return false;
    }
}

//返回按键
const onClickLeft = () => {
  proxy.$router.back();
};

//新增地址
const ToAdd = () => {
  proxy.$router.push("/business/address/add");
};
//编辑地址
// const ToEdit = (item) => proxy.$router.push(`/business/address/edit?addrid=${item.id}`);  与下面的作用一样
const ToEdit = (item) => proxy.$router.push({ path: "/business/address/edit",query:{addrid:item.id}});
</script>